package jfinal42.ctrl;

import jfinal42.model.News;

import java.io.File;
import java.util.*;

import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

public class NewsController extends Controller {
	//
	public static final int PAGESIZE = 10;

	// ip:port/root/news,默认，请求方法index
	// 请求地址栏可以参数
	// ip:80080/jfinal42/news/p1-p2-p2
	// ip:80080/jfinal42/news?p1=v1&p2=v2&p3=v3
	public void index() {
		// 分页
		int pageNo = 1;
		// super.getParaToInt("");

		pageNo = super.getParaToInt(0, 1);
		Long cid = super.getParaToLong(1, null);
		String where = "";
		List<Long> params = new ArrayList<Long>(0);
		if (cid != null) {
			where = " where cate_id=?";
			params.add(cid);
			super.setAttr("cid", cid);
		}
		// 查询
		Page<News> page = News.DAO.paginate(pageNo, PAGESIZE,
				"select id,title,pub_date", " from news " + where
						+ " order by pub_date desc", params.toArray());
		// request

		super.setAttr("p", page);
		// 转发到视图
		super.render("/WEB-INF/jsp/news.jsp");
	}

	public void show() {
		long id = super.getParaToLong(0);
		News n = News.DAO.findById(id);
		// n.getComments();//用到才读

		super.setAttr("news", n);
		super.render("/WEB-INF/jsp/shownews.jsp");
	}

	// 只是跳转一下
	public void toAdd() {
		super.render("/WEB-INF/jsp/add.jsp");
	}

	public void del() {
		Long nid = super.getParaToLong(0);
		boolean istrue = News.DAO.deleteById(nid);
		if (istrue) {
			redirect("/news/1");
			return;
		}
		super.renderJavascript("<script>alert('删除失败！');history.back();</script>");
	}

	public void add() {
		// news
		UploadFile f = super.getFile("nfile");
		LogKit.info("file path=" + f.getFile().getAbsolutePath());
		String path = PathKit.getWebRootPath();
		LogKit.info("path===" + path);
		f.getFile().renameTo(
				new File(path + "/images", f.getOriginalFileName()));

		// News s = super.getModel(News.class, "news");
		News s = super.getModel(News.class);
		s.set("imagepath", "images/" + f.getOriginalFileName());
		LogKit.info("news:" + s);
		boolean isok = s.save();
		if (isok) {
			super.setSessionAttr("msg", "保存成功");

			redirect("/news/1");
			return;
		} else {
			super.renderHtml("<script>alert('失败');history.back();</script>");
		}

	}
}
